<template>
  <div class="login">
    <div class="formbox">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.user_name"
            prefix-icon="el-icon-user"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            prefix-icon="el-icon-warning"
            placeholder="请输入密码"
            type="password"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">登录</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from "@/utils/api.js";
export default {
  name: "login",
  data() {
    return {
      form: {
        user_name: "admin",
        password: "123456",
      },
      rules: {
        user_name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            pattern: /^[a-zA-Z]\w{4,}$/,
            message: "字母开头至少5位字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 18,
            message: "长度在 3 到 18 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    onSubmit() {
      this.$router.push("/home/index");
      login(this.form).then((res) => {
        console.log(res);

        let obj = {
          user: this.form.username,
          time: Date.now(),
          expire: 1000 * 60 * 60,
        };
        this.$message({
          message: "恭喜你,登录成功",
          type: "success",
        });
        localStorage.setItem("user", JSON.stringify(obj));
      });
    },
    // 登录
    // onSubmit() {
    //   this.$refs.form.validate(async (valid, b) => {
    //     // console.log(valid, b)
    //     if (valid) {
    //       let res = await this.$axios({
    //         url: "http://elm.cangdu.org/admin/login",
    //         method: "post",
    //         data: this.form,
    //       });
    //       if (res.data.status === 200) {
    //         // 保存token
    //         this.$message({
    //           message: "恭喜你，登录成功",
    //           type: "success",
    //         });
    //         localStorage.token = res.data.token;
    //         this.$router.push("/index");
    //       } else {
    //         this.$message({
    //           message: "很抱歉，登陆失败！",
    //         });
    //       }
    //     }
    //   });
    // },
  },
};
</script>

<style lang="scss" scoped>
.login {
  background-color: #2b4b6b;
  height: 100%;
  .formbox {
    width: 500px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    padding: 20px;
  }
}
</style>